package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BlogServiceImpl blogService;

    @Autowired
    private FollowServiceImpl followService;

    @Override
    public Result queryById(Long id) {
        Blog blog = this.baseMapper.selectById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }

        String key = "blog:like:" + id;
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        blog.setIsLike(stringRedisTemplate.opsForZSet().score(key, userId.toString()) != null);

        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = "blog:like:" + id;
        Double isLike = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (isLike != null){
            boolean flag = blogService.update()
                    .setSql("liked = liked - 1").eq("id", id).update();
            if (flag){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else{
            // 修改点赞数量
            boolean flag = blogService.update()
                    .setSql("liked = liked + 1").eq("id", id).update();
            if (flag){
                // 修改存储由Set为zSet，按照时间戳排序
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }

        }
        return Result.ok();
    }


    @Override
    public Result queryLikes(Long id) {
        String key = "blog:like:" + id;
        // 取出排行榜，只取出五名
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 5);
        if (range == null || range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 将set中的string集合转为str，并用，分割
        String join = StrUtil.join(",", range);
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());

        // 按照拼接字符串查询
        List<UserDTO> res = userService.query()
                .in("id", ids).last("order by field(id, " + join + ")").list()
                .stream()
                .map(item -> BeanUtil.copyProperties(item, UserDTO.class))
                .collect(Collectors.toList());


        return Result.ok(res);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = blogService.save(blog);
        if (!save){
            return Result.fail("保存博文失败");
        }
        // 查询粉丝
        List<Follow> follows = followService.list(new QueryWrapper<Follow>().eq("follow_user_id", user.getId()));
        for (Follow follow : follows) {
            String key = "feeds:" + follow.getUserId();
            // 推送
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }
}
